package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.StringUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.ui.view.ComplexSortPopWindow;
import com.taptech.doufu.ui.view.IntelligentSortPopWindow;
import com.taptech.doufu.bean.NovelSortBean;
import com.taptech.doufu.bean.NovelSortDataBean;
import com.taptech.doufu.bean.NovelSortJsonBean;
import com.taptech.doufu.bean.NovelSortUpBean;
import com.taptech.doufu.ui.viewholder.personalcenter.MessageViewHolderFactory;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.URLParseUtils;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rx.Observer;

/**
 * Created by lsy on 2015/9/28.
 */
public class NewAlbumsActivity extends DiaobaoBaseActivity implements HttpResponseListener ,View.OnClickListener
{

    // UI控件
    private MyRecyclerView listView;
    private RecyclerViewAdapterAsListView adapter;
    private WaitDialog dialog;
    private TextView mTitle;
    private String tempSting;

    // 数据

    private String url, titleName, uiSource;
    private boolean rankFlag = false;
    private List<MineAbstractBean> mDataList;
    private String last = "";
    private boolean hasMoreContent = true;
    private MessageViewHolderFactory viewHolderFactory;

    private View  sortHeaderLayout,headerSortLine;
    private ImageView complexArrImag,intelligentArrImg;

    private ComplexSortPopWindow complexSortPopWindow;
    private IntelligentSortPopWindow intelligentSortPopWindow;
    private TextView tvHelp;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_albums_activity_layout);
        initData();
        initView();
        HomeMainServices.getInstance().loadAlbumsList(this, url, last ,getFilterData());
        getSortData();
    }

    public void onHelpClick(View view) {
        Intent intent = new Intent();
        intent.setClass(NewAlbumsActivity.this, BrowseActivity.class);
        intent.putExtra(Constant.URL, "http://api.doufu.la/index.php/journal/detail?id=242");
        startActivity(intent);
    }

    private void initView()
    {
        mTitle = (TextView) findViewById(R.id.activity_albums_layout_title);
        tvHelp = (TextView) findViewById(R.id.tvHelp);
        if (titleName != null) {
            mTitle.setText(titleName);
            if (titleName.equals("日更")){
                tvHelp.setVisibility(View.VISIBLE);
            }else{
                tvHelp.setVisibility(View.GONE);
            }
        }
        listView = (MyRecyclerView) findViewById(R.id.albums_listview);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        listView.setLayoutManager(manager);
        adapter = new RecyclerViewAdapterAsListView(this, mDataList);
        listView.setAdapter(adapter);
        listView.setLoadMoreEnable(true);
        listView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                loadMoreData();
                TTLog.d("tag", "the listview has been to bottom");
            }
        });

        sortHeaderLayout =  findViewById(R.id.sort_header);
        headerSortLine =  findViewById(R.id.sort_header_line);

        //是否显示筛选
        if(StringUtil.stringLength(url) && url.indexOf("smart_filter=1") != -1){
            complexArrImag = (ImageView) findViewById(R.id.sort_header_complex_arr_img);
            intelligentArrImg = (ImageView) findViewById(R.id.sort_header_intelligent_arr_img);

            sortHeaderLayout.setVisibility(View.VISIBLE);
            headerSortLine.setVisibility(View.VISIBLE);
            findViewById(R.id.sort_header_complex_layout).setOnClickListener(this);
            findViewById(R.id.sort_header_intelligent_layout).setOnClickListener(this);


        }

    }

    private void initData()
    {
        titleName = getIntent().getStringExtra(Constant.NAME);
        url = getIntent().getStringExtra(Constant.URL);
        //titleName = "推送";
        // url = "http://api.doufu.la/index.php/albums/items?id=93";
        rankFlag = getIntent().getBooleanExtra(Constant.RANK_FALG, false);
        mDataList = new ArrayList<MineAbstractBean>();
        viewHolderFactory = new MessageViewHolderFactory();
    }

    private synchronized void loadMoreData()
    {
        if (hasMoreContent)
        {
            hasMoreContent = false;
            HomeMainServices.getInstance().loadAlbumsList(this, url, last);
        }
    }

    private void loadPulldata(){
        last = "";
        if(mDataList != null){
            mDataList.clear();
        }
        if(adapter != null){
            adapter.notifyDataSetChanged();
        }
        HomeMainServices.getInstance().loadAlbumsList(this, url, last ,getFilterData());
    }
    @Override
    public void handleResponse(int handleType, final HttpResponseObject response)
    {
        if (response == null)
        {
            UIUtil.toastMessage(this, Constant.loadingFail);
            return;
        }

        switch (handleType)
        {
            case HomeMainServices.HANDLE_TYPE_LOAD_ALBUMS:
                JSONObject data = (JSONObject) response.getData();

                try {
                    // 如果还有更多内容
                    List<? extends MineAbstractBean> dataList = null;

                    if (titleName.equals("完结"))
                    {
                        tempSting= URLParseUtils.parseA(url);

                        if (response.getStatus() == Constant.STATUS_SUCCESS)
                        {
                            try
                            {
                                if ((last == null) || (last.equals("")))
                                {
                                    new Thread(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                        }
                                    }).start();
                                }
                            } catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                            dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("main"));
                        } else
                        {
                            if ((last == null) || (last.equals("")))
                            {
                                try
                                {
                                    UIUtil.toastMessage(NewAlbumsActivity.this, DiaobaoUtil.getErrorTips(response));
                                    data = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                    dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("main"));
                                } catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else
                    {
                        if ((data.has("items")))
                        {
                            dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("items"));
                        } else
                        {
                            if ((data.has("list")) && (viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("list")) != null))
                            {
                                dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("list"));
                            }else if ((data.has("novels")) && (viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("novels")) != null))
                            {
                                dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("novels"));
                            }
                        }
                    }
                    if (dataList != null && data.has("last") && !data.getString("last").equals(last))
                    {

                        if (rankFlag)
                        {
                            for (int i = 0; i < dataList.size(); i++)
                            {
                                dataList.get(i).setRank_flag(true);
                            }
                        }
                        hasMoreContent = true;
                        mDataList.addAll(dataList);
                        adapter.notifyDataSetChanged();
                    }


                    //adapter.notifyItemRangeInserted(mDataList.size() - dataList.size(), dataList.size());
                    else
                    {
                        hasMoreContent = false;
                        adapter.pullComplete(true);

                    }
                    last = data.getString("last");
                } catch (Exception e)
                {
                    UIUtil.toastMessage(this, Constant.loadingFail);
                }

                break;
        }
    }

    /*public void back(View view)
    {
        super.back(view);
    }*/

    private NovelSortDataBean novelSortDataBean;
    private void getSortData(){
        ApiClient.getInstance().getService().getNovelSortDataBean()
                .compose(RxJavaHelper.<NovelSortDataBean>observeOnMainThread(this))
                .subscribe(new Observer<NovelSortDataBean>() {
                    @Override
                    public void onCompleted() {
                        Log.d("getSortData====","onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("getSortData====","onError");
                    }

                    @Override
                    public void onNext(NovelSortDataBean bean) {
                        Log.d("getSortData====","novelSortDataBean");
                        novelSortDataBean = bean;
                    }
                });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sort_header_complex_layout:
                if(complexSortPopWindow != null && complexSortPopWindow.isShowing()){
                    complexSortPopWindow.dismiss();
                    return;
                }

                getComplexSortBean();

                if(intelligentSortPopWindow != null && intelligentSortPopWindow.isShowing()){
                    intelligentSortPopWindow.dismiss();
                }

                if(complexSortPopWindow == null){
                    complexSortPopWindow = new ComplexSortPopWindow(NewAlbumsActivity.this,complexSortBena);
                }


                complexSortPopWindow.setNovelSortUpBean(complexSortBena);
                complexSortPopWindow.setComplexSelSort(new ComplexSortPopWindow.ComplexSelSort() {
                    @Override
                    public void selSortListener(NovelSortUpBean sortUpbean) {
                        complexSortBena = sortUpbean;
                        loadPulldata();
                    }
                });
                complexSortPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        complexArrImag.setImageResource(R.drawable.cp_up);
                    }
                });
                complexArrImag.setImageResource(R.drawable.cp_down);
                complexSortPopWindow.showAsDropDown(headerSortLine);
                break;

            case R.id.sort_header_intelligent_layout:
                if(intelligentSortPopWindow != null && intelligentSortPopWindow.isShowing()){
                    intelligentSortPopWindow.dismiss();
                    return;
                }
                getIntelligentSortBean();

                if(complexSortPopWindow != null && complexSortPopWindow.isShowing()){
                    complexSortPopWindow.dismiss();
                }

                if(intelligentSortPopWindow == null){
                    intelligentSortPopWindow = new IntelligentSortPopWindow(NewAlbumsActivity.this,intelligenSortList);
//                    intelligentSortPopWindow.setNovelSortUpBeanList(intelligenSortList);
                }
                intelligentSortPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        intelligentArrImg.setImageResource(R.drawable.cp_up);
                    }
                });
                intelligentArrImg.setImageResource(R.drawable.cp_down);
                intelligentSortPopWindow. setIntelligentSortSelSortListener(new IntelligentSortPopWindow.IntelligentSortSelSort() {
                    @Override
                    public void selSortListener(List<NovelSortUpBean> beens) {
                        if (intelligenSortList != null) {
                            intelligenSortList.clear();
                            intelligenSortList.addAll(beens);
                        }
                        loadPulldata();
                    }
                });
                intelligentSortPopWindow.showAsDropDown(headerSortLine);
                break;
        }
    }

    private  NovelSortUpBean complexSortBena;
    private NovelSortUpBean getComplexSortBean(){
        if(complexSortBena != null && complexSortBena.getList()!= null ){
            return complexSortBena ;
        }
        List<NovelSortBean> orderList = null;
        if (novelSortDataBean != null && novelSortDataBean.getData() != null) {
            orderList = novelSortDataBean.getData().getOrder();
        }
        if(orderList != null && orderList.size() > 0){
            complexSortBena = new NovelSortUpBean();
            complexSortBena.setSelNovelSortBean(orderList.get(0));
            complexSortBena.setList(orderList);
        }
        return complexSortBena ;
    }

    private  List<NovelSortUpBean> intelligenSortList;
    private List<NovelSortUpBean> getIntelligentSortBean(){

        if(intelligenSortList != null ){
            return intelligenSortList ;
        }

        if (novelSortDataBean != null && novelSortDataBean.getData() != null) {
            intelligenSortList = novelSortDataBean.getData().getWhere();
        }

        if (intelligenSortList != null) {
            for(int i = 0 ; i < intelligenSortList.size();i ++ ){
                NovelSortUpBean novelSortUpBean = intelligenSortList.get(i);
                List<NovelSortBean> novelSortBeanList = novelSortUpBean.getList();

                NovelSortBean selNovelSortBean = novelSortUpBean .getSelNovelSortBean();
                if( selNovelSortBean == null && novelSortBeanList != null && novelSortBeanList.size() > 0){
                    selNovelSortBean = novelSortBeanList.get(0);
                    novelSortUpBean.setSelNovelSortBean(selNovelSortBean);
                }
            }
        }

        return intelligenSortList ;
    }

    private String getFilterData (){
        String data = "";
        NovelSortJsonBean dataBean = new NovelSortJsonBean();
        if(complexSortBena != null && complexSortBena.getSelNovelSortBean() != null){
            List<NovelSortBean> orderList = new ArrayList<>();
            orderList.add(complexSortBena.getSelNovelSortBean());
            dataBean.setOrder(orderList);
        }

        if(intelligenSortList != null && intelligenSortList.size() > 0){
            List<NovelSortUpBean> whereList = new ArrayList<>();
            for(int i = 0;i < intelligenSortList.size() ; i++){
                setSortChild(whereList ,intelligenSortList.get(i));
            }
            dataBean.setWhere(whereList);
        }
        if(dataBean.getOrder() == null && dataBean.getWhere() == null){
            return  null;
        }
        data =  com.alibaba.fastjson.JSONObject.toJSONString(dataBean);
        Log.d("data", "data===" +data );
        return data ;
    }

    private  void setSortChild (List<NovelSortUpBean> novelSortUpBeanList ,NovelSortUpBean sortUpBean){
        NovelSortUpBean novelSortUpBean = new NovelSortUpBean();
        List<NovelSortBean>  list = new ArrayList<>();
        list.add(sortUpBean.getSelNovelSortBean());
        novelSortUpBean.setKey(sortUpBean.getKey());
        novelSortUpBean.setTitle(sortUpBean.getTitle());
        novelSortUpBean.setList(list);
        novelSortUpBeanList.add(novelSortUpBean);
    }
}
